/**
 * Copyright @ 2000 ysten Co. Ltd. 
 * All right reserved.     
 * @author: wangmin
 * date: 2016-07-01     
 */
package com.task.utils;

import com.google.gson.GsonBuilder;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.cert.CertificateException;

/**
 * https请求工具
 */
public class HttpsUtils {

    private static DefaultHttpClient client;

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpsUtils.class);


    /**
     * 访问https的网站
     *
     * @param httpclient
     */
    private static void enableSSL(DefaultHttpClient httpclient) {
        //调用ssl
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[]{truseAllManager}, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme https = new Scheme("https", sf, 443);
            httpclient.getConnectionManager().getSchemeRegistry().register(https);
        } catch (Exception e) {
            LOGGER.error("enableSSL error {}",e);
        }
    }

    /**
     * 重写验证方法，取消检测ssl
     */
    private static TrustManager truseAllManager = new X509TrustManager() {

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {

        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {

        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

    };

    public static String get(String url) {
        // 创建HttpClient实例
        if (client == null) {
            client = new DefaultHttpClient();
            enableSSL(client);
        }

        // 创建Get方法实例
        HttpGet httpsGet = new HttpGet(url);

        String result = "";
        try {
            HttpResponse response = client.execute(httpsGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(response.getEntity());
                // Do not need the rest
                httpsGet.abort();
            }
        } catch (ClientProtocolException e) {
            LOGGER.error("ClientProtocolException error {}",e);
        } catch (IllegalStateException e) {
            LOGGER.error("IllegalStateException error {}",e);
        } catch (IOException e) {
            LOGGER.error("IOException error {}",e);
        }
        return result;
    }

    public static String post(String url,String data) {
        // 创建HttpClient实例
        if (client == null) {
            client = new DefaultHttpClient();
            enableSSL(client);
        }

        // 创建Post方法实例
        HttpPost httpPost = new HttpPost(url);
        StringEntity postEntity = new StringEntity(data, "UTF-8");
        httpPost.setEntity(postEntity );
        String result = "";
        try {
            HttpResponse response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(response.getEntity());
                // Do not need the rest
                httpPost.abort();
            }
        } catch (ClientProtocolException e) {
            LOGGER.error("ClientProtocolException error {}",e);
        } catch (IllegalStateException e) {
            LOGGER.error("IllegalStateException error {}",e);
        } catch (IOException e) {
            LOGGER.error("IOException error {}",e);
        }
        return result;
    }

/*    public static void main(String[] args) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=6NP_ZSx0MU3lW5Od5h5R6APzIqWTy2Qneex28UMrBYzD24f7ZQUGuQedFHCZNf1k";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userid","haixinke_wangmin@163.com");
        jsonObject.put("agentid","1");
        System.out.println(jsonObject.toString());
        String result = post(url,jsonObject.toString());
        System.out.println(result);
        JSONObject obj = JsonUtils.fromJson(result,JSONObject.class);
        System.out.println("*********" + new GsonBuilder().create().toJson(obj));
        System.out.println("############" + obj.get("openid"));
//        String data = "{\n" +"\"userid\": \"haixinke_wangmin@163.com\",\n" +"\"agentid\": 1\n" +"}";
    }*/
}


